package com.xuxin.nantai.activity.chou;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.king.zxing.Intents;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.xuxin.nantai.R;
import com.xuxin.nantai.activity.MyCaptureActivity;
import com.xuxin.nantai.base.BaseActivity;
import com.xuxin.nantai.base.BaseConstant;
import com.xuxin.nantai.bean.BaseBean;
import com.xuxin.nantai.bean.SelectBean;
import com.xuxin.nantai.contract.SelectContract;
import com.xuxin.nantai.presenter.SelectPresenter;
import com.xuxin.nantai.utils.ACache;
import com.xuxin.nantai.utils.FlowingUtils;

import org.jetbrains.annotations.NotNull;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.06.11 0011
 * 缝制抽检
 */
public class SelectActivity extends BaseActivity implements SelectContract.View {
    private SelectContract.Presenter presenter = new SelectPresenter(this);
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;

    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smart_refresh;
    @BindView(R.id.smart_recycle)
    RecyclerView smart_recycle;
    @BindView(R.id.smart_empty)
    ImageView smart_empty;

    private EditText complete_name;
    private EditText complete_inspect;


    private SelectAdapter myAdapter;
    private int page_num = 1;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_smart);
    }

    @Override
    public void initView() {
        title_name.setText("缝制抽检");
        title_right.setVisibility(View.VISIBLE);
        smart_refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                handler.sendEmptyMessage(0);
            }
        });
        myAdapter = new SelectAdapter();
        smart_recycle.setLayoutManager(new LinearLayoutManager(this));
        smart_recycle.setItemViewCacheSize(BaseConstant.page_limit);
        smart_recycle.setNestedScrollingEnabled(false);
        smart_recycle.setAdapter(myAdapter);
        View view = View.inflate(this, R.layout.head_complete, null);
        view.findViewById(R.id.complete_query).setOnClickListener(this);
        view.findViewById(R.id.complete_scan).setOnClickListener(this);
        complete_name = view.findViewById(R.id.complete_name);
        complete_inspect = view.findViewById(R.id.complete_inspect);
        myAdapter.addHeaderView(view);
        myAdapter.addChildClickViewIds(R.id.item_select_update, R.id.item_select_detail,
                R.id.item_select_delete);
        myAdapter.setOnItemChildClickListener((adapter, view1, position) -> {
            switch (view1.getId()) {
                case R.id.item_select_update:
                    try {
                        Bundle bundle = new Bundle();
                        bundle.putString("Guid", myAdapter.getData().get(position).getGuid());
                        bundle.putString("ID", myAdapter.getData().get(position).getID());
                        bundle.putString("teamType", myAdapter.getData().get(position).getTeamType());
                        bundle.putInt("reCheck", myAdapter.getData().get(position).getIsReCheck());
                        bundle.putString("flowingCode", myAdapter.getData().get(position).getFlowingCode());
                        bundle.putString("cInvName", myAdapter.getData().get(position).getcInvName());
                        bundle.putString("cInvCode", myAdapter.getData().get(position).getcInvCode());
                        bundle.putString("packNum", myAdapter.getData().get(position).getPackQty());
                        bundle.putString("comNum", myAdapter.getData().get(position).getComNum());
                        bundle.putString("percent", myAdapter.getData().get(position).getCheckRate_FZ());
                        bundle.putString("checkNum", myAdapter.getData().get(position).getCheckNum());
                        bundle.putString("area", myAdapter.getData().get(position).getFacArea());
                        bundle.putString("groupName", myAdapter.getData().get(position).getGroupName());
                        bundle.putString("groupCode", myAdapter.getData().get(position).getGroupCode());
                        bundle.putString("inspectorName", myAdapter.getData().get(position).getInspectorName());
                        bundle.putString("inspectorCode", myAdapter.getData().get(position).getInspectorCode());
                        bundle.putString("inspectorTime", myAdapter.getData().get(position).getInspectTime());
                        bundle.putString("result", myAdapter.getData().get(position).getResult());
                        bundle.putString("mark", myAdapter.getData().get(position).getRemark());
                        ActivityUtils.startActivityForResult(bundle, SelectActivity.this,
                                SelectUpdateActivity.class, BaseConstant.result_code);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.item_select_detail:
                    try {
                        Bundle bundle_detail = new Bundle();
                        bundle_detail.putString("ID", myAdapter.getData().get(position).getID());
                        ActivityUtils.startActivityForResult(bundle_detail, SelectActivity.this,
                                SelectDetailActivity.class, BaseConstant.result_code);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.item_select_delete:
                    new MaterialDialog.Builder(SelectActivity.this)
                            .content("确定删除这条数据？")
                            .positiveText("确定")
                            .negativeText("取消")
                            .onPositive((dialog, which) -> {
                                try {
                                    Message message = Message.obtain();
                                    message.what = 1;
                                    Bundle data = new Bundle();
                                    data.putString("Guid", myAdapter.getData().get(position).getGuid());
                                    message.setData(data);
                                    handler.sendMessage(message);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            })
                            .show();
                    break;
            }
        });
        String UserName = ACache.get(this).getAsString("UserName");
        LogUtils.e("UserName = " + UserName);
        if (!StringUtils.isEmpty(UserName)) {
            complete_inspect.setText(UserName);
        }
    }

    @Override
    public void initData() {
        page_num = 1;
        myAdapter.setList(null);
        smart_refresh.setEnableLoadMore(true);
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onComplete() {
        smart_refresh.finishRefresh();
        smart_refresh.finishLoadMore();
        smart_empty.setVisibility(myAdapter.getData().isEmpty() ? View.VISIBLE : View.GONE);
    }

    @Override
    @OnClick({R.id.title_left, R.id.title_right})
    public void onClick(View view) {
        KeyboardUtils.hideSoftInput(this);
        switch (view.getId()) {
            case R.id.title_left:
                finish();
                break;
            case R.id.title_right:
                ActivityUtils.startActivityForResult(this, SelectUpdateActivity.class, BaseConstant.result_code);
                break;
            case R.id.complete_query:
                initData();
                break;
            case R.id.complete_scan:
                startActivityForResult(new Intent(this, MyCaptureActivity.class), BaseConstant.result_scan);
                break;
        }
    }

    public Handler handler = new Handler(message -> {
        String LoginName = ACache.get(this).getAsString("LoginName");
        String UserName = ACache.get(this).getAsString("UserName");
        switch (message.what) {
            case 0:
                String name = complete_name.getText().toString();
                String inspect = complete_inspect.getText().toString();
                presenter.getSelect(LoginName, name, inspect, page_num);
                break;
            case 1:
                String Guid = message.getData().getString("Guid");
                presenter.delete(UserName, Guid);
                break;
        }
        return false;
    });

    @Override
    public void onSuccess(SelectBean selectBean) {
        myAdapter.addData(selectBean.getData().getSewSpot());
        if (selectBean.getData().getTotalCount() > myAdapter.getData().size()) {
            page_num++;
        } else {
            smart_refresh.setEnableLoadMore(false);
        }
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        initData();
        ToastUtils.showShort(baseBean.getMessage());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == BaseConstant.result_code) {
            initData();
            LogUtils.e("返回刷新");
        }
        if (requestCode == BaseConstant.result_scan && null != data && null != data.getExtras()) {
            //处理扫描结果（在界面上显示）
            String result = FlowingUtils.getFlowing(data.getStringExtra(Intents.Scan.RESULT));
            if (StringUtils.isEmpty(result)) {
                ToastUtils.showShort("请填写流转单号");
            } else {
                LogUtils.e("result = " + result);
                complete_name.setText(result);
                initData();
            }
        }
    }

    private static class SelectAdapter extends BaseQuickAdapter<SelectBean.DataBean.SewSpotBean, BaseViewHolder> {

        public SelectAdapter() {
            super(R.layout.item_select);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder holder, SelectBean.DataBean.SewSpotBean item) {
            holder.setText(R.id.item_select_team, "组检/单检 : " + item.getTeamType());
            holder.setText(R.id.item_select_flowing, "流转单号 : " + item.getFlowingCode());
            holder.setText(R.id.item_select_name, "成品名称 : " + item.getcInvName());
            holder.setText(R.id.item_select_pack, "本包数 : " + item.getPackQty());
            holder.setText(R.id.item_select_com, "部件数 : " + item.getComNum());
            holder.setText(R.id.item_select_percent, "抽检比例 : " + item.getCheckRate_FZ());
            holder.setText(R.id.item_select_check, "抽检数 : " + item.getCheckNum());
            holder.setText(R.id.item_select_inspector, "巡检员 : " + item.getInspectorName());
            holder.setText(R.id.item_select_group, "生产组别 : " + item.getGroupName());
            holder.setText(R.id.item_select_week, "周次 : " + item.getWeekNo());
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.CHINA);
                sdf.setLenient(false);
                Date newDate = sdf.parse(item.getInspectTime());
                sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                item.setInspectTime(sdf.format(newDate));
            } catch (ParseException e) {
                e.printStackTrace();
            } finally {
                holder.setText(R.id.item_select_time, "检验日期 : " + item.getInspectTime());
            }
            holder.setText(R.id.item_select_area, "厂区 : " + item.getFacArea());
            holder.setText(R.id.item_select_reCheck, "是否复检 : " + (1 == item.getIsReCheck() ? "是" : "否"));
            holder.setText(R.id.item_select_mark, "备注 : " + item.getRemark());
            holder.setText(R.id.item_select_decide, "判定结果 : " + item.getResult());
            holder.setText(R.id.item_select_defect, "疵点数 : " + item.getDefectNum());
        }
    }
}